package com.cskaoyan.service.promote;

import com.cskaoyan.bean.promote.Advertising;
import com.cskaoyan.bean.promote.AdvertisingExample;
import com.cskaoyan.bean.promote.base.PromotePageData;
import com.cskaoyan.bean.promote.base.PromoteParam;
import com.cskaoyan.bean.promote.bo.AdvertisingSearchBO;
import com.cskaoyan.bean.promote.exception.AddAdvertisingException;
import com.cskaoyan.bean.promote.exception.DeleteAdvertisingException;
import com.cskaoyan.bean.promote.exception.UpdateAdvertisingException;
import com.cskaoyan.mapper.promote.AdvertisingMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author liXiaoFei
 * @date 2021/10/18 17:08
 */
@Service
public class AdvertisingServiceImpl implements AdvertisingService {

    @Autowired
    AdvertisingMapper advertisingMapper;

    @Override
    public PromotePageData queryAdvertising(PromoteParam promoteParam, AdvertisingSearchBO advertisingSearchBO) {

        AdvertisingExample example = new AdvertisingExample();
        AdvertisingExample.Criteria criteria = example.createCriteria();

        if (advertisingSearchBO.getContent() != null && !"".equals(advertisingSearchBO.getContent())){
            criteria.andContentLike("%" + advertisingSearchBO.getContent() + "%");
        }
        if (advertisingSearchBO.getName() != null && !"".equals(advertisingSearchBO.getName())){
            criteria.andNameLike("%" + advertisingSearchBO.getName() + "%");
        }

        //设置排序
        example.setOrderByClause(promoteParam.getSort() + " " + promoteParam.getOrder());
        List<Advertising> advertisings = advertisingMapper.selectByExample(example);
        return PromotePageData.ok(advertisings);
    }

    @Override
    public Advertising addAdvertising(Advertising advertising) throws AddAdvertisingException {
        int code = advertisingMapper.insertSelective(advertising);
        if (code == 0) throw new AddAdvertisingException();
        return advertising;
    }

    @Override
    public Advertising updateAdvertising(Advertising advertising) throws UpdateAdvertisingException {
        advertising.setUpdateTime(new Date(System.currentTimeMillis()));
        int code = advertisingMapper.updateByPrimaryKeySelective(advertising);
        if (code == 0) throw new UpdateAdvertisingException();
        return advertising;
    }

    @Override
    public void deleteAdvertising(Advertising advertising) throws DeleteAdvertisingException {
        int code = advertisingMapper.updateByPrimaryKeySelective(advertising);
        if (code == 0) throw new DeleteAdvertisingException();
    }


}
